package edu.hawaii.duedates.webapp;

import edu.hawaii.duedates.datastore.User;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.validation.validator.EmailAddressValidator;

/**
 * The login page.
 * 
 * @author Daniel Arakaki, Jeho Jung, Arthur Shum, Daniel Tian.
 */
public class LoginPage extends WebPage {
  
  /** Support serialization. */
  private static final long serialVersionUID = 1L;

  private String email;
  private String password;
    
  /**
   * Adds components to the webpage.
   */
  public LoginPage() {

    add(HeaderContributor.forCss(
        edu.hawaii.duedates.webapp.LoginPage.class, "LoginPage.css", "screen"));
    add(HeaderContributor.forCss(
        edu.hawaii.duedates.webapp.LoginPage.class, "GlobalStyle.css", "screen"));

    //add(new FeedbackPanel("feedback"));
    add(createLoginForm());
  }

  /**
   * Create the login form.
   * @return the login form to add to the webpage.
   */
  private Form createLoginForm() {
    Form form = new Form("form") {
      private static final long serialVersionUID = 1L;
      @Override
      public void onSubmit() {        
//      ConfigurationManager cm = new ConfigurationManager();
        for (User user : getMySession().getDueDatesConfig().getUsers()) {
          if (user.isValidUser(email, password)) {
            getMySession().setIsLoggedIn();
            getMySession().setUser(user);
            getMySession().setSmtpServer(getMySession().getDueDatesConfig().getSmtpServer());
            setResponsePage(HomePage.class);
          }
          else {
            // display in the feedbackpanel
            info("Invalid login!");
            email = "";
          }
        } // for
      } // onSubmit()
    };

    TextField tf = new TextField("email", new PropertyModel(this, "email")); 
    tf.setRequired(true);
    tf.add(EmailAddressValidator.getInstance());
    form.add(tf);

    form.add(new PasswordTextField("password", new PropertyModel(this, "password")));

    form.add(new FeedbackPanel("feedback"));

    return form;    
  }
  
  /**
   * Returns the current session.
   * 
   * @return the current session.
   */
  private DueDatesSession getMySession() {
    return (DueDatesSession) getSession();
  }

}
